package com.micro.ai.models.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.micro.ai.commons.exception.BusinessException;
import com.micro.ai.models.entity.ModelDefinition;
import com.micro.ai.models.mapper.ModelDefinitionMapper;
import com.micro.ai.models.service.ModelDefinitionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;

/**
 * 模型定义服务实现
 * 
 * @author micro-ai
 * @since 0.0.1
 */
@Slf4j
@Service
public class ModelDefinitionServiceImpl extends ServiceImpl<ModelDefinitionMapper, ModelDefinition> implements ModelDefinitionService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ModelDefinition create(ModelDefinition modelDefinition) {
        if (modelDefinition == null) {
            throw new BusinessException("M0000", "模型定义信息不能为空");
        }
        
        // 验证必填字段
        if (!StringUtils.hasText(modelDefinition.getTenantId())) {
            throw new BusinessException("M0000", "租户ID不能为空");
        }
        if (!StringUtils.hasText(modelDefinition.getModelName())) {
            throw new BusinessException("M0000", "模型名称不能为空");
        }
        if (!StringUtils.hasText(modelDefinition.getVendorId())) {
            throw new BusinessException("M0000", "供应商ID不能为空");
        }
        if (!StringUtils.hasText(modelDefinition.getTypeId())) {
            throw new BusinessException("M0000", "类型ID不能为空");
        }
        
        // 检查模型名称是否已存在（同一租户下）
        LambdaQueryWrapper<ModelDefinition> nameQuery = new LambdaQueryWrapper<>();
        nameQuery.eq(ModelDefinition::getTenantId, modelDefinition.getTenantId())
                 .eq(ModelDefinition::getModelName, modelDefinition.getModelName());
        ModelDefinition existing = this.getOne(nameQuery);
        if (existing != null) {
            throw new BusinessException("M0001", "模型名称已存在: " + modelDefinition.getModelName());
        }
        
        // 设置默认值
        if (modelDefinition.getContextLength() == null || modelDefinition.getContextLength() <= 0) {
            modelDefinition.setContextLength(4096);
        }
        if (modelDefinition.getMaxOutputTokens() == null || modelDefinition.getMaxOutputTokens() <= 0) {
            modelDefinition.setMaxOutputTokens(2000);
        }
        if (modelDefinition.getStatus() == null) {
            modelDefinition.setStatus("active");
        }
        if (modelDefinition.getSupportFunctions() == null) {
            modelDefinition.setSupportFunctions(false);
        }
        if (modelDefinition.getSupportVision() == null) {
            modelDefinition.setSupportVision(false);
        }
        if (modelDefinition.getSupportFineTuning() == null) {
            modelDefinition.setSupportFineTuning(false);
        }
        
        LocalDateTime now = LocalDateTime.now();
        modelDefinition.setCreatedAt(now);
        modelDefinition.setUpdatedAt(now);
        
        boolean success = this.save(modelDefinition);
        if (!success) {
            throw new BusinessException("M0003", "保存模型定义失败");
        }
        
        log.info("创建模型定义成功: modelId={}, modelName={}", 
                modelDefinition.getId(), modelDefinition.getModelName());
        
        return modelDefinition;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ModelDefinition update(String id, ModelDefinition modelDefinition) {
        if (!StringUtils.hasText(id)) {
            throw new BusinessException("M0000", "模型ID不能为空");
        }
        if (modelDefinition == null) {
            throw new BusinessException("M0000", "模型定义信息不能为空");
        }
        
        ModelDefinition existing = this.getById(id);
        if (existing == null) {
            throw new BusinessException("M0002", "模型定义不存在: " + id);
        }
        
        modelDefinition.setId(id);
        modelDefinition.setUpdatedAt(LocalDateTime.now());
        
        boolean success = this.updateById(modelDefinition);
        if (!success) {
            throw new BusinessException("M0003", "更新模型定义失败");
        }
        
        log.info("更新模型定义成功: modelId={}, modelName={}", id, modelDefinition.getModelName());
        
        return modelDefinition;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(String id) {
        if (!StringUtils.hasText(id)) {
            throw new BusinessException("M0000", "模型ID不能为空");
        }
        
        ModelDefinition model = this.getById(id);
        if (model == null) {
            throw new BusinessException("M0002", "模型定义不存在: " + id);
        }
        
        // 注意：由于外键约束，如果有关联的模型配置、微调任务等，数据库会自动阻止删除
        // 这里可以提供更友好的错误提示，但不需要手动检查关联关系
        
        boolean success = this.removeById(id);
        if (!success) {
            throw new BusinessException("M0003", "删除模型定义失败");
        }
        
        log.info("删除模型定义成功: modelId={}, modelName={}", id, model.getModelName());
    }

    @Override
    public Page<ModelDefinition> pageQuery(int pageNum, int pageSize, String tenantId, String keyword, String vendorId, String typeId, String status) {
        if (pageNum < 1) {
            pageNum = 1;
        }
        if (pageSize < 1 || pageSize > 100) {
            pageSize = 20;
        }
        
        Page<ModelDefinition> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<ModelDefinition> query = new LambdaQueryWrapper<>();
        
        if (StringUtils.hasText(tenantId)) {
            query.eq(ModelDefinition::getTenantId, tenantId);
        }
        if (StringUtils.hasText(vendorId)) {
            query.eq(ModelDefinition::getVendorId, vendorId);
        }
        if (StringUtils.hasText(typeId)) {
            query.eq(ModelDefinition::getTypeId, typeId);
        }
        if (StringUtils.hasText(status)) {
            query.eq(ModelDefinition::getStatus, status);
        }
        if (StringUtils.hasText(keyword)) {
            query.and(q -> q.like(ModelDefinition::getModelName, keyword)
                          .or().like(ModelDefinition::getModelAlias, keyword)
                          .or().like(ModelDefinition::getDescription, keyword));
        }
        
        query.orderByDesc(ModelDefinition::getCreatedAt);
        
        return this.page(page, query);
    }
}

